from transformers import ChineseCLIPProcessor, ChineseCLIPModel
import torch
import hashlib


class Model_Loader:
    model = None
    processor = None


def get_clip_model(model_path):
    if Model_Loader.model is not None and Model_Loader.processor is not None:
        return Model_Loader.model, Model_Loader.processor
    from config.Common import get_clip_device
    import time

    # 使用CLIP模型独立的设备配置
    device = get_clip_device()

    print(f"[CLIP模型] 开始加载模型到设备: {device}")
    load_start = time.time()

    Model_Loader.model = ChineseCLIPModel.from_pretrained(model_path).to(device)
    Model_Loader.processor = ChineseCLIPProcessor.from_pretrained(model_path)

    load_time = time.time() - load_start
    print(f"[CLIP模型] 模型加载完成，耗时: {load_time:.3f}秒，设备: {device}")

    return Model_Loader.model, Model_Loader.processor


def calculate_md5_from_bytes(image_bytes):
    """从图片字节内容计算MD5哈希值"""
    hash_md5 = hashlib.md5()
    try:
        hash_md5.update(image_bytes)
        return hash_md5.hexdigest()
    except Exception as e:
        print(f"从字节计算MD5失败: {str(e)}")
        return None


